<template>
  <div class="account">
    <el-form ref="formRefEl" :rules="rules" label-width="60px" :model="formAccountAlign" style="max-width: 330px">
      <el-form-item label="账号" prop="name">
        <el-input size="large" v-model="formAccountAlign.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input size="large" show-password v-model="formAccountAlign.password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useLoginStore } from '@/stores/login'
import type { ElForm } from 'element-plus'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'

const formAccountAlign = reactive<IAccount>({
  name: localCache.getCache('name') ?? '',
  password: localCache.getCache('password') ?? ''
})

const rules = reactive({
  name: [
    { required: true, message: '用户名不能为空!', trigger: 'blur' },
    { min: 4, max: 12, message: '必须是4-12位字母', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空!', trigger: 'blur' },
    { min: 4, max: 18, message: '必须是4-18位', trigger: 'blur' }
  ]
})

const loginStore = useLoginStore()
const formRefEl = ref<InstanceType<typeof ElForm>>()

function accountAlian(isRememberPwd: boolean) {
  formRefEl.value?.validate((valid: IAccount) => {
    if (valid) {
      loginStore.getLoginAccount(formAccountAlign).then((res) => {
        // 登录成功后拿到是否记住密码来进行存储用户名和密码
        if (isRememberPwd) {
          localCache.setCache('name', formAccountAlign.name)
          localCache.setCache('password', formAccountAlign.password)
        } else {
          localCache.removeCache('name')
          localCache.removeCache('password')
        }
      })
    } else {
      ElMessage({
        showClose: true,
        message: '失败!',
        type: 'error'
      })
      return false
    }
  })
}

defineExpose({
  accountAlian
})
</script>

<style lang="less" scoped>
.el-form-item {
  margin-right: 20px;
}
</style>
